from flask import Blueprint, render_template, abort
from models import Lesson, Vocabulary, LessonText, Annotation, CultureTip
from exts import db

bp = Blueprint("content", __name__, url_prefix="/content")


@bp.route("/index01")
def index01():
    """课程中心首页"""
    return render_template("index01.html")

@bp.route("/index02")
def index02():
    """课程中心首页"""
    return render_template("index02.html")

@bp.route("/index03")
def index03():
    """课程中心首页"""
    return render_template("index03.html")


@bp.route('/lesson/<int:lesson_id>')
def lesson_detail(lesson_id):
    """课程详情页（保持模板路径不变）"""
    try:
        # 检查课程是否存在
        lesson = Lesson.query.get(lesson_id)
        if not lesson:
            abort(404, description=f"Lesson {lesson_id} not found")

        # 使用更高效的查询方式
        query_params = {"lesson_id": lesson_id}

        # 添加查询结果验证
        vocabularies = Vocabulary.query.filter_by(**query_params).all()
        if not vocabularies:
            print(f"警告：课程 {lesson_id} 没有找到词汇数据")

        return render_template(
            'index_content.html',  # 保持原模板路径
            lesson=lesson,
            all_vocabularies=vocabularies,
            texts=LessonText.query.filter_by(**query_params)
            .order_by(LessonText.order_num)
            .all(),
            annotations=Annotation.query.filter_by(**query_params)
            .order_by(Annotation.order_num)
            .all(),
            culture_tips=CultureTip.query.filter_by(**query_params).first()
        )
    except Exception as e:
        # 添加详细错误日志
        print(f"加载课程失败：{str(e)}")
        abort(500, description="服务器内部错误")